USE Lib
GO

---------------------------------------------------------------------------
-- BEGIN MAINTENANCE WRAPPER
----------------------------
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'FN' AND name = 'fn_count_distinct_val') BEGIN
	DROP  FUNCTION  tsql.fn_count_distinct_val
	PRINT '<<< DROP FUNCTION tsql.fn_count_distinct_val - Completed with SUCCESS >>>'
END
GO
----------------------------
-- END MAINTENANCE WRAPPER
---------------------------------------------------------------------------

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


/*================================================================================================
Name:			tsql.fn_count_distinct_val
Type:			User defined function 
Owner:					
Description:	Returns distinct count of list items from a coma sepparated list of values 
Parameters:		@list = list of values comma delimited
Dependens on:  	fn_split_xt
Usage:			SELECT [tsql].[fn_count_distinct_val] ('1,2,3,4,5',6)
--------------------------------------------------------------------------------------------------
Project:		http://sqllib.codeplex.com/
Help:			http://sqllib.codeplex.com/wikipage?title=fn_count_val&referringTitle=Documentation		
Version:		20120904
SrcCtrlApp:		SVN
SrcCtrlPath:	http://sqllib.codeplex.com/SourceControl/list/changesets
--------------------------------------------------------------------------------------------------
History:		09/04/2012 - Adrian E Dudau - Function created
================================================================================================*/

CREATE FUNCTION [tsql].[fn_count_distinct_val] (@list NVARCHAR(MAX))
RETURNS BIGINT
AS

BEGIN
	DECLARE @Result AS BIGINT	

	-- If the List is empty or null return input string
	SET @Result = 0

	-- Else get min
	IF ISNULL(@list,'') <> '' BEGIN
		SELECT @Result = COUNT(DISTINCT item_value) FROM [tsql].[fn_split](@list,',')
	END

	RETURN @Result 
END

GO

---------------------------------------------------------------------------
-- BEGIN MAINTENANCE WRAPPER
-- Verify completion
----------------------------
IF EXISTS(SELECT * FROM sysobjects WHERE type = 'FN' AND name = 'fn_count_distinct_val') BEGIN 
	PRINT '<<< CREATE FUNCTION tsql.fn_count_distinct_val - Completed with SUCCESS >>>'
END

ELSE BEGIN 
	PRINT '<<< CREATE FUNCTION tsql.fn_count_distinct_val - Completed with ERROR >>>'
END

GO
----------------------------
-- END MAINTENANCE WRAPPER
---------------------------------------------------------------------------


